package com.yj.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.yj.model.Course;
import com.yj.model.Sc;
import com.yj.model.Student;

@Controller("studentAction")
@Scope("prototype")
public class StudentAction extends BaseAction<Student> {

	private static final long serialVersionUID = 1L;

	public String getCourses() {
		if(session.get("student") == null) {
			return "login";
		}
		HttpServletRequest hsRequest = ServletActionContext.getRequest();
		String type = (String)hsRequest.getParameter("type");
		System.out.println(type);
		if(type.equals("已选课程") || type.equals("专选")) {
			return type;
		}
		request.put("courses", courseService.getCoursesByType(type));
		return type;
	}
	
	public String selectCourse() {
		if(session.get("student") == null) {
			return "login";
		}
		HttpServletRequest hsRequest = ServletActionContext.getRequest();
		Integer cid = Integer.parseInt(hsRequest.getParameter("cid"));
		Course course = courseService.getById(cid);
		Sc sc = new Sc(course,(Student)session.get("student"));
	    Student student = (Student) session.get("student");
	    String type = course.getType();
	    for(Sc s:student.getScs()) {
	    	if(s.getCourse().getType().equals(type)) {
	    		request.put("message", "已存在" + type + "类型课程，不允许重复选课!");
	    		request.put("selectedCourse", course);
	    		return "已选课程";
	    	}
	    }
	    scService.save(sc);
	    
	    course.setSelected(course.getSelected() + 1);
	    courseService.update(course);
	    
		session.put("student",(Student) userService.login(student, 1));
		request.put("message", "选课成功!");
		request.put("selectedCourse", course);
		return "已选课程";
	}
	
	public String dropCourse() {
		if(session.get("student") == null) {
			return "login";
		}
		HttpServletRequest hsRequest = ServletActionContext.getRequest();
		Integer sid = Integer.parseInt(hsRequest.getParameter("sid"));
		Integer cid = Integer.parseInt(hsRequest.getParameter("cid"));
		scService.delete(sid);
		
		Course course = courseService.getById(cid);
	    course.setSelected(course.getSelected() - 1);
	    courseService.update(course);
	    Student student = (Student) session.get("student");
		session.put("student",(Student) userService.login(student, 1));
		request.put("message", "退选成功!");
		request.put("dropedCourse", course);
		return "已选课程";
	}
}
